<?php
/**
 * Created by PhpStorm.
 * User: tony
 * Date: 2018/6/4
 * Time: 11:20
 */

namespace app\modules\v1\controllers;

use app\config\Status;
use app\models\Task;
use app\models\TaskFlow;
use app\modules\v1\controllers\parent\ParentController;
use yii\data\ActiveDataProvider;

class TaskController extends ParentController
{

    public function actionRootNode(){
        return Task::generateRootNode();
    }


    public function actionLevel2Node(){
        $branch_id = \Yii::$app->request->get('branch_id');
        return Task::generateLevel2Node($branch_id);
    }

    public function actionLevel3Node(){
        $branch_id = \Yii::$app->request->get('department_id');
        return Task::generateLevel3Node($branch_id);
    }


    public function actionLevel4Node()
    {
        $user_id = \Yii::$app->request->get('user_id');
        return Task::generateLevel4Node($user_id);
    }

    public function actionLevel5Node()
    {
        $user_id = \Yii::$app->request->get('task_id');
        return Task::generateLevel5Node($user_id);
    }

    /**
     * @return array
     * @throws \yii\base\InvalidConfigException
     */
    public function actionCreate(){
        $params = \Yii::$app->request->getBodyParams();
        $task = new Task();
        $task->load($params,'');
        $task->created_at = $task->updated_at = time();
        $task->source_id = 1;
        $task->type_id = 1;
        $task->status = 1;
        $task->creator_id = \Yii::$app->user->id;
        if($task->save()){
            return [
                'bCode' => Status::SUCCESS,
                'bData' => $task
            ];
        }
        return [
            'bCode' => Status::FAIL,
            'bData' => $task->errors
        ];
    }

    public function actionIndex(){
        $params = \Yii::$app->request->getQueryParams();
        // 关系加条件
        $query = Task::find()
            ->leftJoin('{{%user}} as u','u.id=hj_task.user_id' )
            ->leftJoin('{{%department}} as d', 'd.id = u.department_id')
            ->leftJoin('{{%branch}} as b','b.id = d.branch_id')
            ->with(['taskFlow','user','creator','user.department','user.branch']);
        if(isset($params['user_id']))
            $query->andWhere(['{{%task}}.user_id'=>$params['user_id']]);
        if(isset($params['branch_id']) && $params['branch_id']!=0)
            $query->andWhere(['b.id'=>$params['branch_id']]);
        if(isset($params['status']) && $params['status'] != 0)
            $query->andWhere(['{{%task}}.status'=>$params['status']]);
        if(isset($params['started_at']) && isset($params['ended_at']) && $params['started_at']!='0' && $params['started_at']!='0')
        {
            $query->andWhere(['>=', '{{%task}}.created_at',$params['started_at']]);
            $query->andWhere(['<=', '{{%task}}.created_at',$params['ended_at']+86400]);
        }
        $pageSize = 5;
        if(isset($params['pageSize'])){
            $pageSize = (int)$params['pageSize'];
        }
        return new ActiveDataProvider([
            // 使用with方法实现贪加载
            'query' => $query,
            // 分页信息
            'pagination' => [
                'pageSize' => $pageSize,
            ],
            // 排序信息
            'sort' => [
                'defaultOrder' => [
                    'id' => SORT_DESC,
                ]
            ],
        ]);
    }

    /**
     * @return array
     * @throws \yii\base\InvalidConfigException
     */
    public function actionUpdate(){
        $params = \Yii::$app->request->getBodyParams();
        $id = (int)$params['id'];
        $task = Task::findOne($id);

        if($task) {
            if(!$this->isMine($task->creator_id)){
                return [
                    'bCode' => Status::FAIL,
                    'bData' => ['msg'=>'你只能修改自己录入的任务']
                ];
            }
            $task->load($params,'');
            $task->updated_at = time();
//            $task->source_id = 1;
//            $task->type_id = 1;
//            $task->status = 1;
            if($task->save()){
                return [
                    'bCode' => Status::SUCCESS,
                    'bData' => $task
                ];
            }
            return [
                'bCode' => Status::FAIL,
                'bData' => $task->errors
            ];
        }
        return [
            'bCode' => Status::FAIL,
            'bData' => ['msg'=>'找不到该ID的记录']
        ];

    }

    /**
     * 完成任务或改变任务状态专用接口
     * @return array
     * @throws \yii\base\InvalidConfigException
     */
    public function actionChangeTaskStatus(){
        $params = \Yii::$app->request->getBodyParams();
        $id = (int)$params['id'];
        $task = Task::findOne($id);

        if($task) {
            if(!$this->isMine($task->user_id)){
                return [
                    'bCode' => Status::FAIL,
                    'bData' => ['msg'=>'你只能完成自己的任务']
                ];
            }
            $task->status = (int)$params['status'];
            $task->updated_at = time();
//            $task->source_id = 1;
//            $task->type_id = 1;
//            $task->status = 1;
            if($task->save()){
                return [
                    'bCode' => Status::SUCCESS,
                    'bData' => $task
                ];
            }
            return [
                'bCode' => Status::FAIL,
                'bData' => $task->errors
            ];
        }
        return [
            'bCode' => Status::FAIL,
            'bData' => ['msg'=>'找不到该ID的记录']
        ];

    }

    /**
     * @return Task|null
     */
    public function actionView(){
        $params = \Yii::$app->request->get('id');
        $id = (int)$params;
        $task = Task::findOne($id);
        return $task;
    }

    /**
     * @return array
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public function actionDelete(){
        $params = \Yii::$app->request->get('id');
        $id = (int)$params;
        $task = Task::findOne($id);
        if($task){
            if(!$this->isMine($task->creator_id)){
                return [
                    'bCode' => Status::FAIL,
                    'bData' => ['msg'=>'你只能删除自己录入的任务']
                ];
            }
            $taskFlow = TaskFlow::find()->where(['task_id'=>$id])->limit(1)->one();
            if($taskFlow){
                return [
                    'bCode' => Status::FAIL,
                    'bData' => ['msg'=>'该任务已经产生执行节点，无法删除']
                ];
            }

            $task->delete();
            return [
                'bCode' => Status::SUCCESS,
                'bData' => $task
            ];
        }

        return [
            'bCode' => Status::FAIL,
            'bData' => ['msg'=>'找不到该ID的记录']
        ];
    }
}